package com.xinnet.mms.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.entity.Notice;
import com.xinnet.mms.notice.service.NoticeService;
/**
 * 
 * 
 * @author 王湛智[wangzhanzhi@xinnet.com]
 *
 * @version 1.0
 *
 * @since 2014年2月17日
 *
 */
@Controller
@RequestMapping("/notice")
public class NoticeController {
	@Autowired
	private NoticeService noticeService;
	private SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**用于生成新2级路径*/
	private int dir1;
	private int dir2;
	/**通用路径分隔符*/
	private String sep=java.io.File.separator;
	
	/**
	 * 
	 * 功能描述：显示消息列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月17日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/msg/{pageNow}")
	public String showMessageList(@PathVariable int pageNow,HttpServletRequest request,HttpServletResponse response) throws SQLException {
		PageView<Notice> pageView=new PageView<Notice>();
		pageView.setPageNow(pageNow);
		request.setAttribute("pageView", pageView);
		pageView=noticeService.queryMessage(pageView);
		if(pageView!=null)
		request.setAttribute("msgList", pageView.getRecords());
		request.setAttribute("pageView", pageView);
		return "market/notice/noticelist";
	}
	/**
	 * 
	 * 功能描述：通过id查看消息详情
	 *
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月17日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/msgInfo")
	public String showMessageInfo(HttpServletRequest request,HttpServletResponse response,String id) throws SQLException, IOException {
		PrintWriter writer=response.getWriter();
		Notice notice=noticeService.getMessageById(id);
		StringBuffer str=new StringBuffer("");
		str
		.append(notice.getId()).append("#$")
		.append(notice.getMsgTitle()).append("#$")
		.append(notice.getContent()).append("#$");
		writer.print(str.toString());
		return null;
	}
	/**
	 * 
	 * 功能描述：通过id删除消息记录
	 *
	 * @param request
	 * @param response
	 * @param ids
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月17日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/delMsg")
	public String delMessage(HttpServletRequest request,HttpServletResponse response,String id) throws SQLException, IOException {
		PrintWriter writer=response.getWriter();
		noticeService.delMessageById(id);
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：修改消息
	 *
	 * @param request
	 * @param response
	 * @param id
	 * @param msgTitle
	 * @param msgContent
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月17日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/updateMsg")
	public String updateMessage(HttpServletRequest request,HttpServletResponse response,String id,String msgTitle,String msgContent) throws SQLException, IOException {
		PrintWriter writer=response.getWriter();
		Notice notice=new Notice();
		notice.setId(id);
		notice.setContent(msgContent);
		notice.setMsgTitle(msgTitle);
		noticeService.updateMessageById(notice);
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：修改消息
	 *
	 * @param request
	 * @param response
	 * @param msgTitle
	 * @param msgContent
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月17日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/newMsg")
	public String newMessage(HttpServletRequest request,HttpServletResponse response,String msgTitle,String msgContent) throws SQLException, IOException {
		PrintWriter writer=response.getWriter();
		Emp emp=(Emp) request.getSession().getAttribute("currentUser");
		Notice notice=new Notice();
		notice.setId(UUID.randomUUID().toString());
		notice.setContent(msgContent);
		notice.setMsgTitle(msgTitle);
		notice.setPubTime(sf.format(new Date()));
		notice.setReportMessage(1);
		notice.setOrgId(emp.getId());
		noticeService.addMessage(notice);
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：根据标题查询消息列表
	 *
	 * @param request
	 * @param response
	 * @param msgTitle
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws UnsupportedEncodingException 
	 *
	 * @since 2014年2月17日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/searchMsg/{pageNow}")
	public String showMessageListByTitle(@PathVariable int pageNow,HttpServletRequest request,HttpServletResponse response,String msgTitle,String timeUp,String timeDown) throws SQLException, UnsupportedEncodingException {
		Notice notice=new Notice();
		notice.setMsgTitle(java.net.URLDecoder.decode(msgTitle,"UTF-8"));
		notice.setTimeUp(timeUp);
		notice.setTimeDown(timeDown);
		request.getSession().setAttribute("msgTerm", notice);
		PageView<Notice> pageView=new PageView<Notice>();
		pageView.setPageNow(pageNow);
		request.setAttribute("pageView", pageView);
		pageView=noticeService.queryMsgByTitle(pageView, notice);
		if(pageView!=null)
		request.setAttribute("msgList", pageView.getRecords());
		return "market/notice/noticelist";
	}
	/**
	 * 
	 * 功能描述：显示公告列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月18日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/policy/{pageNow}")
	public String showPolicyList(@PathVariable int pageNow,HttpServletRequest request,HttpServletResponse response) throws SQLException {
		PageView<Notice> pageView=new PageView<Notice>();
		pageView.setPageNow(pageNow);
		request.setAttribute("pageView", pageView);
		pageView=noticeService.queryPolicy(pageView);
		request.setAttribute("pageView", pageView);
		if(pageView!=null)
			request.setAttribute("policyList", pageView.getRecords());
		return "market/notice/policylist";
	}
	/**
	 * 
	 * 功能描述：带条件查询公告列表
	 *
	 * @param request
	 * @param response
	 * @param msgTitle
	 * @param timeUp
	 * @param timeDown
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws UnsupportedEncodingException 
	 *
	 * @since 2014年2月18日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/searchPolicy/{pageNow}")
	public String showPolicyListByTitle(@PathVariable int pageNow,HttpServletRequest request,HttpServletResponse response,String msgTitle,String timeUp,String timeDown) throws SQLException, UnsupportedEncodingException {
		Notice notice=new Notice();
		notice.setMsgTitle(java.net.URLDecoder.decode(msgTitle,"UTF-8"));
		notice.setTimeUp(timeUp);
		notice.setTimeDown(timeDown);
		request.getSession().setAttribute("msgTerm", notice);
		PageView<Notice> pageView=new PageView<Notice>();
		pageView.setPageNow(pageNow);
		request.setAttribute("pageView",pageView);
		pageView=noticeService.queryPolicy(pageView,notice);
		if(pageView!=null)
			request.setAttribute("policyList", pageView.getRecords());
		return "market/notice/policylist";
	}
	/**
	 * 
	 * 功能描述：通过id查看公告详情
	 *
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月17日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/policyInfo")
	public String showPolicyInfo(HttpServletRequest request,HttpServletResponse response,String id) throws SQLException, IOException {
		PrintWriter writer=response.getWriter();
		Notice notice=noticeService.getPolicyById(id);
		StringBuffer str=new StringBuffer("");
		str
		.append(notice.getId()).append("#$")
		.append(notice.getMsgTitle()).append("#$")
		.append(notice.getContent()).append("#$");
		writer.print(str.toString());
		return null;
	}
	/**
	 * 
	 * 功能描述：通过id删除公告记录
	 *
	 * @param request
	 * @param response
	 * @param ids
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月17日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/delPolicy")
	public String delPolicy(HttpServletRequest request,HttpServletResponse response,String id) throws SQLException, IOException {
		PrintWriter writer=response.getWriter();
		noticeService.delPolicyById(id);
		writer.print(1);
		return null;
	}
	/**
	 * 
	 * 功能描述：修改公告
	 *
	 * @param request
	 * @param response
	 * @param id
	 * @param msgTitle
	 * @param msgContent
	 * @param filePath
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月17日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/updatePolicy")
	public String updatePolicy(HttpServletRequest request,HttpServletResponse response,String titleHidden,String msgTitle,String msgContent,@RequestParam(value = "picx", required = false) MultipartFile picx) throws SQLException, IOException {
		//获取真实路径
		String path=request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
		String fullPath="";
		//获取文件名称
		String picName = picx.getOriginalFilename();
		Notice notice=new Notice();
		if(picName==null||picName.equals("")) {
			//封装公告数据
			notice.setId(titleHidden);
			notice.setContent(msgContent);
			notice.setMsgTitle(msgTitle);
			notice.setPubTime(sf.format(new Date()));
			//添加公告
			noticeService.updatePolicyById(notice);
			return showPolicyList(1,request,response);
		}
		else {
			//文件格式正确则进行上传
			if(uploadCheck(picName)) {
				//生成新路径 用以安全 以及减少文件夹过于拥挤导致读取缓慢
				path=makePath(picName,path);
				//生成新文件名 用以安全 以及认证唯一
				picName=makeName(picName);
				File file=new File(path,picName);
				//上传
				picx.transferTo(file);
				fullPath+=sep+"upload"+sep+dir1+sep+dir2+sep;
				//封装公告数据
				notice.setId(titleHidden);
				notice.setContent(msgContent);
				notice.setMsgTitle(msgTitle);
				notice.setPubTime(sf.format(new Date()));
				notice.setFilePath(fullPath+picName);
				//添加公告
				noticeService.updatePolicyById(notice);
				return showPolicyList(1,request,response);
			}
			request.setAttribute("error", "上传格式错误");
			return "errors/error";
		}
	}
	/**
	 * 
	 * 功能描述：添加公告 上传相关
	 *
	 * @param request
	 * @param response
	 * @param msgTitle
	 * @param msgContent
	 * @Param filePath
	 * @return
	 * @throws SQLException
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月17日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/newPolicy")
	public String newPolicy(HttpServletRequest request,HttpServletResponse response,String msgTitleAdd,String msgContentAdd,@RequestParam(value = "pic", required = false) MultipartFile pic) throws SQLException, IOException {
		Emp emp=(Emp) request.getSession().getAttribute("currentUser");
		//获取真实路径
		String path=request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
		String fullPath="";
		//获取文件名称
		String picName = pic.getOriginalFilename();
		Notice notice=new Notice();
		if(picName==null||picName.equals("")) {
			//封装公告数据
			notice.setId(UUID.randomUUID().toString());
			notice.setContent(msgContentAdd);
			notice.setMsgTitle(msgTitleAdd);
			notice.setPubTime(sf.format(new Date()));
			notice.setReportMessage(0);
			notice.setOrgId(emp.getId());
			//添加公告
			noticeService.addPolicy(notice);
			return showPolicyList(1,request,response);
		}
		else {
			//文件格式正确则进行上传
			if(uploadCheck(picName)) {
				//生成新路径 用以安全 以及减少文件夹过于拥挤导致读取缓慢
				path=makePath(picName,path);
				//生成新文件名 用以安全 以及认证唯一
				picName=makeName(picName);
				File file=new File(path,picName);
				//上传
				pic.transferTo(file);
				fullPath+=sep+"upload"+sep+dir1+sep+dir2+sep;
				//封装公告数据
				notice.setId(UUID.randomUUID().toString());
				notice.setContent(msgContentAdd);
				notice.setMsgTitle(msgTitleAdd);
				notice.setPubTime(sf.format(new Date()));
				notice.setReportMessage(0);
				notice.setOrgId(emp.getId());
				notice.setFilePath(fullPath+picName);
				//添加公告
				noticeService.addPolicy(notice);
				return showPolicyList(1,request,response);
			}
			request.setAttribute("error", "上传格式错误");
			return "errors/error";
		}
	}
	/**
	 * 
	 * 功能描述：显示政策公告详情页面
	 *
	 * @return
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws SQLException 
	 * @throws UnsupportedEncodingException 
	 *
	 * @since 2014年2月18日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("msgDetails")
	public String showMsgDetails(HttpServletRequest request,HttpServletResponse response,String id) throws SQLException, UnsupportedEncodingException {
		request.setAttribute("policy", noticeService.getPolicyById(id));
		return "market/notice/msgdetails";
	}
	/**
	 * 
	 * 功能描述：下载附件
	 *
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年2月18日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping("/download")
	public String download(HttpServletRequest request,HttpServletResponse response,String url) throws IOException {
		String realPath=request.getSession().getServletContext().getRealPath("/WEB-INF");
		//设置下载文件名
		url=java.net.URLDecoder.decode(url,"UTF-8");
		url=realPath+url;
		String fileName=url.substring(url.lastIndexOf(sep));
		fileName=fileName.substring(fileName.lastIndexOf("_")+1);
		fileName=URLEncoder.encode(fileName, "UTF-8");
		response.addHeader("content-disposition","attachment;filename="+fileName);
		response.setHeader("content-type","text/html;charset=utf-8");
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		//下载操作
		File file=new File(url);
		OutputStream out=response.getOutputStream();
		InputStream in=new FileInputStream(file);
		byte[] b=new byte[1024];
		@SuppressWarnings("unused")
		int ch=0;
		while((ch=in.read(b))!=-1) {
			out.write(b,0,b.length);
		}
		in.close();
		return null;
	}
	
	/**
	 * 
	 * 功能描述：显示图片上传页面
	 *
	 * @return
	 *
	 * @author 王志军
	 *
	 * @since 2014年2月18日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/toPicUpload")
	public String toUpload(HttpServletRequest request,HttpServletResponse response) {
		
		return "market/notice/picUpload";
	}
	
	/**
	 * 
	 * 功能描述：首页图片上传
	 *
	 * @throws SQLException
	 *
	 * @author 王志军[wangzhijun@xinnet.com]
	 *
	 * @since 2014年2月18日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/upload")
	public String picUpload(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		// 解析器解析request的上下文
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 先判断request中是否包涵multipart类型的数据，
		if (multipartResolver.isMultipart(request)) {
			// 再将request中的数据转化成multipart类型的数据
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			MultiValueMap<String, MultipartFile> fileMap = multiRequest
					.getMultiFileMap();
			Set<String> attrNameSet = fileMap.keySet();
			Iterator<String> iter = multiRequest.getFileNames();
			Iterator<String> itSet = attrNameSet.iterator();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile((String) iter.next());
				if (file != null) {
					String fileName = file.getOriginalFilename();
					if (fileName == null || "".equals(fileName)) {
						itSet.next();
						continue;
					}
					String path = request.getSession().getServletContext()
							.getRealPath("/common");

					File localFile = new File(path + File.separator + "images"
							+ File.separator + itSet.next() + ".png");

					// 写文件到本地
					try {
						file.transferTo(localFile);
						model.put("msg", "上传成功！");
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						model.put("msg", "上传失败！");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						model.put("msg", "上传失败！");
					}
				}
			}
		}
		return "market/notice/picUpload";
	}
	
	/**
	 * 
	 * 功能描述：将文件名字更改成唯一
	 *
	 * @return
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月18日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	
	public String makeName(String picName) {
		return UUID.randomUUID().toString()+"_"+picName;
	}
	/**
	 * 
	 * 功能描述：将上传路径更改
	 *
	 * @return
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月18日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public String makePath(String fileName,String filePath) {
		int hashCode=fileName.hashCode();
		dir1=hashCode&0xf;
		dir2=(hashCode>>4)&0xf;
		String path=filePath+sep+dir1+sep+dir2+sep;
		File file=new File(path);
		if(!file.exists())
			file.mkdirs();
		return path;
	}
	
	/**
	 * 
	 * 功能描述：验证文件格式
	 *
	 * @param picName
	 * @return
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月18日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	private boolean uploadCheck(String picName) {
		picName=picName.substring(picName.lastIndexOf(".")).toLowerCase();
		if(
			picName.equals(".doc")||
			picName.equals(".docx")||
			picName.equals(".ppt")||
			picName.equals(".xlsx")||
			picName.equals(".xls")||
			picName.equals(".jpg")||
			picName.equals(".jpeg")||
			picName.equals(".png")||
			picName.equals(".ico")||
			picName.equals(".bmp")||
			picName.equals(".gif")||
			picName.equals(".rar")||
			picName.equals(".zip")||
			picName.equals(".7z")||
			picName.equals(".txt")
			)
			return true;
		return false;
	}
}
